package com.stone.customer.infra.lock.impl;

import com.stone.customer.infra.lock.RedisLock;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.util.Collections;
import java.util.UUID;

/**
 * 可重入redis分布式锁实现
 *
 * @author Mr_wenpan@163.com 2021/07/23 22:47
 */
public class ReentrantRedisLock implements RedisLock {

    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 设定好锁对应的key
     */
    private final String key;

    /**
     * 存入的线程信息的前缀，防止与其他jvm中的线程信息冲突
     */
    private final String ID_PREFIX = UUID.randomUUID().toString() + Thread.currentThread().getId();

    public ReentrantRedisLock(StringRedisTemplate stringRedisTemplate, String key) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.key = key;
    }

    private static final DefaultRedisScript<Long> LOCK_SCRIPT;
    private static final DefaultRedisScript<Object> UNLOCK_SCRIPT;

    static {
        // 加载获取锁的脚本
        LOCK_SCRIPT = new DefaultRedisScript<>();
        LOCK_SCRIPT.setScriptSource(new ResourceScriptSource(new ClassPathResource("script.lua/lock.lua")));
        LOCK_SCRIPT.setResultType(Long.class);

        // 加载释放锁的脚本
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setScriptSource(new ResourceScriptSource(new ClassPathResource("script.lua/unlock.lua")));
    }

    /**
     * 释放锁的时间
     */
    private String releaseTime;

    @Override
    public boolean tryLock(long releaseTime) {
        this.releaseTime = String.valueOf(releaseTime);
        Long result = stringRedisTemplate.execute(LOCK_SCRIPT, Collections.singletonList(key), ID_PREFIX, this.releaseTime);
        return result != null && result.intValue() == 1;
    }

    @Override
    public void unlock() {
        stringRedisTemplate.execute(UNLOCK_SCRIPT, Collections.singletonList(key), ID_PREFIX);
    }
}
